package com.laolang.thresh.module.system.user.business;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Sets;
import com.laolang.thresh.module.auth.consts.AuthConsts;
import com.laolang.thresh.module.auth.util.SecurityUtil;
import com.laolang.thresh.module.system.user.business.mapper.SysUserPermBusinessMapper;
import com.laolang.thresh.module.system.user.entity.SysRole;
import com.laolang.thresh.module.system.user.service.SysRoleService;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 系统用户权限业务常用方法.
 *
 * @author laolang
 * @version 0.1
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class SysUserPermBusiness {

    private final SysUserPermBusinessMapper sysUserPermBusinessMapper;
    private final SysRoleService sysRoleService;

    public Set<String> listPermsByUsername(String username) {
        if (StrUtil.equals(username, AuthConsts.SUPER_ADMIN_USER_NAME)) {
            return Sets.newHashSet(AuthConsts.ALL_PERMISSION);
        }
        Set<String> perms = sysUserPermBusinessMapper.listRolesByUsername(username);
        return perms.stream().filter(StrUtil::isNotBlank).collect(Collectors.toSet());
    }

    public Set<String> listRolesByUsername(String username) {
        if (StrUtil.equals(username, AuthConsts.SUPER_ADMIN_USER_NAME)) {
            List<SysRole> sysRoles = sysRoleService.list();
            if (CollUtil.isEmpty(sysRoles)) {
                return Sets.newHashSet();
            }
            return sysRoles.stream().map(SysRole::getCode).filter(code -> !StrUtil.isBlank(code))
                .collect(Collectors.toSet());
        }
        Set<String> roles = sysUserPermBusinessMapper.listRolesByUsername(username);
        return roles.stream().filter(StrUtil::isNotBlank).collect(Collectors.toSet());
    }
}
